package com.meiyou.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;




import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.meiyou.aliUtils.OrderInfoUtil2_0;
import com.meiyou.mapper.MeiyouChongzhiMapper;
import com.meiyou.mapper.UserMapper;
import com.meiyou.pojo.AliPayInfo;
import com.meiyou.pojo.MeiyouChongzhi;
import com.meiyou.pojo.MeiyouZfb;
import com.meiyou.service.AlipayService;
import com.meiyou.service.AppSettingService;
import com.meiyou.service.ChongzhiService;
import com.meiyou.service.ThirdService;
import com.meiyou.service.UserService;
import com.meiyou.service.ZfbService;
import com.meiyou.utils.Context;
import com.meiyou.utils.GenerateOrderNoUtil;
import com.meiyou.utils.Msg;
import com.meiyou.utils.ShareCodeUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


@Controller
@Api(value = "支付宝接口调用控制器", tags = { "支付宝接口" })
public class AlipayController {

	@Autowired
	AlipayService alipay;
	 
	@Autowired
	ThirdService third;
	
	@Autowired
	UserService userservice;
	
	@Autowired
	ChongzhiService chongzhiService;
	

	@Autowired
	MeiyouChongzhiMapper meiyouchongzhiMapper;
	
	@Autowired
	AppSettingService appsettingService;
	
	@Autowired
	ZfbService zfbservice;
	
	
	/**
	 * 绑定支付宝提现账号
	 * @return
	 */
	@RequestMapping(value = "bindAlipay")
	@ResponseBody
	@ApiOperation(value="绑定支付宝",notes="绑定支付宝")
	public Msg bindAlipay(HttpServletRequest request, HttpServletRequest response,String z_count,String z_name) {
		if(request.getSession().getAttribute("user")!=null) {
			MeiyouZfb zfb = new MeiyouZfb();
			zfb.setzCount(z_count);
			zfb.setzName(z_name);
			zfb.setzUCount(request.getSession().getAttribute("user").toString());
			return zfbservice.binZfb(zfb);
			
		}else {
			Msg msg = Msg.fail();
			msg.setMsg("请先登录");
			return msg;
		}
		
	}
	
	/**
	 * 查询是否绑定
	 */
	@RequestMapping(value="selBindZfb",method=RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="查询是否绑定支付宝",notes="查询是否绑定支付宝")
	public Msg selBindZfb(HttpServletRequest req) {
		Msg msg;
		if(req.getSession().getAttribute("user")==null) {
			msg = Msg.fail();
			msg.setMsg("请先登录");
			return msg;
		}else {
			msg = Msg.success();
			Map<String,Object> map = new HashMap<String,Object>();
			
			List<MeiyouZfb> list = zfbservice.selZfb(req.getSession().getAttribute("user").toString());
			if(list==null||list.size()==0) {
				map.put("bind", false);
			}else {
				map.put("bind", true);
				map.put("zname", list.get(0).getzName());
				map.put("zcount", list.get(0).getzCount());
			}
			msg.setExtend(map);
			return msg;
		}
		
		
	}
	
	
	
	/**
	 * 获取充值比例
	 * @return
	 */
	@RequestMapping(value = "getChongZhiBiLi")
	@ResponseBody
	@ApiOperation(value="获取充值比例",notes="获取充值比例")
	public Msg getChongZhiBiLi(HttpServletRequest request, HttpServletRequest response) {
		Msg msg;
		String bili = appsettingService.selChongzhiBili();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("bili", bili);
		msg= Msg.success();
		msg.setExtend(map);
		return msg;
	}
	
	/**
	 * 支付宝支付结果回调
	 * @return
	 */
	@RequestMapping(value = "/alipayReturnNotice")
	public ModelAndView  alipayReturnNotice(HttpServletRequest request, HttpServletRequest response) {
		
		System.out.println("支付成功, 进入同步通知接口...");
		//获取支付宝GET过来反馈信息
				Map<String,String> params = new HashMap<String,String>();
				Map<String,String[]> requestParams = request.getParameterMap();
				for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
					String name = (String) iter.next();
					String[] values = (String[]) requestParams.get(name);
					String valueStr = "";
					for (int i = 0; i < values.length; i++) {
						valueStr = (i == values.length - 1) ? valueStr + values[i]
								: valueStr + values[i] + ",";
					}
					//乱码解决，这段代码在出现乱码时使用
					try {
						valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();	
					}
					params.put(name, valueStr);
				}

				boolean signVerified = false;
				try{
					signVerified = AlipaySignature.rsaCheckV1(params, Context.SXALIPAY_PUBLIC_KEY, Context.SXCHARSET, Context.SXSIGN_TYPE); //调用SDK验证签名
				}catch (Exception e) {
					System.out.println("SDK验证签名出现异常");
				}

				ModelAndView mv = new ModelAndView("MY1/html/confirm_success");
				//——请在这里编写您的程序（以下代码仅作参考）——
				if(signVerified) {
					//商户订单号
					String out_trade_no;
					//支付宝交易号
					String trade_no;
					//付款金额
					String total_amount;
					try {
						out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

						trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

						total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
						
						
						// 修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
						MeiyouChongzhi chongzhi  = meiyouchongzhiMapper.selectByPrimaryKey(out_trade_no);
						chongzhi.setcCzcode(out_trade_no);
						if(!chongzhi.getcState().equals("完成")) {
							chongzhi.setcState("完成");
							chongzhiService.updateState(chongzhi);
						}
						System.out.println("********************** 支付成功(支付宝同步通知) **********************");
			    		mv.addObject("out_trade_no", out_trade_no);
			    		mv.addObject("trade_no", trade_no);
			    		mv.addObject("total_amount", total_amount);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					

				}else {
					System.out.println("支付, 验签失败...");
				}

				return mv;

		
		
	}
	
	/**
	 * 支付宝申请提现
	 * @return
	 */
	@RequestMapping(value = "aliTixian")
	@ResponseBody
	@ApiOperation(value="支付宝提现",notes="支付宝提现")
	public Msg aliTixian(HttpServletRequest request, HttpServletRequest response,double meijin) {
		Msg msg;
		if(request.getSession().getAttribute("user")!=null) {
		  msg = alipay.zfbTixian(request.getSession().getAttribute("user").toString(), meijin);
		   return msg;
		}else {
			msg = Msg.fail();
			msg.setMsg("请先登录");
			return msg;
		}
	}
		
  
	/**
	 * 支付宝支付结果回调
	 * @return
	 */
	@RequestMapping(value = "payCallback")
	public String payCallback(HttpServletRequest request, HttpServletRequest response) {
		System.out.println("支付成功, 进入异步通知接口...");
		//获取支付宝POST过来反馈信息
		//获取支付宝POST过来反馈信息
				Map<String,String> params = new HashMap<String,String>();
				Map<String,String[]> requestParams = request.getParameterMap();
				for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
					String name = (String) iter.next();
					String[] values = (String[]) requestParams.get(name);
					String valueStr = "";
					for (int i = 0; i < values.length; i++) {
						valueStr = (i == values.length - 1) ? valueStr + values[i]
								: valueStr + values[i] + ",";
					}
					//乱码解决，这段代码在出现乱码时使用
                    try {
						valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					params.put(name, valueStr);
				}
            
				
				boolean signVerified;
				try {
					signVerified = AlipaySignature.rsaCheckV1(params, Context.SXALIPAY_PUBLIC_KEY, Context.SXCHARSET, "RSA2");
				
		
			/*
			 * //支付宝交易号 String out_trade_no = new
			 * String(req.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
			 * 
			 * //订单号 String trade_no = new
			 * String(req.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
			 * 
			 * //交易状态 String trade_status = new
			 * String(req.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
			 */
					
					boolean verify_result;
					
						verify_result = AlipaySignature.rsaCheckV1(params, Context.SXALIPAY_PUBLIC_KEY, Context.SXCHARSET, "RSA2");
						if(signVerified) {//验证成功
							//商户订单号
							String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

							//支付宝交易号
							String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

							//交易状态
							String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

							//付款金额
							String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

							if(trade_status.equals("TRADE_FINISHED")){
								//判断该笔订单是否在商户网站中已经做过处理
								//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
								//如果有做过处理，不执行商户的业务程序
								return "支付未完成";
								//注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
								//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
							}else if (trade_status.equals("TRADE_SUCCESS")){
								//判断该笔订单是否在商户网站中已经做过处理
								//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
								//如果有做过处理，不执行商户的业务程序

								//注意：
								//付款完成后，支付宝系统发送该交易状态通知

								// 修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
								MeiyouChongzhi chongzhi  = meiyouchongzhiMapper.selectByPrimaryKey(out_trade_no);
								if(!chongzhi.getcState().equals("完成")) {
									chongzhi.setcState("完成");
									chongzhiService.updateState(chongzhi);
								}
								System.out.println("********************** 支付成功(支付宝同步通知) **********************");
								
							}
						}
						return "redirect:MY1/html/confirm_success.html";
				}catch(Exception e){
					System.out.println("支付异步通知异常");
					return "redirect:MY1/html/confirm_success.html";
				}//調用sdk验证
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
				//商户订单号
	}
				
						
	
	/**
	 * 支付宝支付
	 * @return
	 */
	@RequestMapping(value = "alipayOrder",method=RequestMethod.GET)
	@ApiOperation(value = "支付宝获取支付订单信息接口")
	public @ResponseBody String alipay(String total_amount,String subject,HttpServletResponse httpResponse,HttpServletRequest req) {
		System.out.println("支付参数"+total_amount+","+subject);
        String out_trade_no = GenerateOrderNoUtil.gen("MEIYOU",100L);
        System.out.println("订单号"+	out_trade_no);
		String form = alipay.getOrderInfo(total_amount, subject, out_trade_no,req);
		return form;
	}	
	
	
	
	
	/**
	 * 支付宝登录
	 * @param code
	 * @return
	 */
	@RequestMapping(value = "alipayLogin", method = RequestMethod.GET)
	@ApiOperation(value = "支付宝登录接口")
	public @ResponseBody Msg alipayLogin(String auth_code,HttpServletRequest req) {
		System.out.println("授权码"+auth_code);
		Msg msg =  alipay.getAliPayInfo(auth_code);//获取支付宝用户信息
		Msg result;
		if(msg.getCode()==100) {
			AliPayInfo info = (AliPayInfo)(msg.getExtend().get("alipayinfo"));
			System.out.println("用户id"+info.getUserId());
			if(alipay.alipayHas(info.getUserId())) { //判断是否存在该支付宝用户
				    String ucount = third.selUcountByZfb(info.getUserId());	
					req.getSession().setAttribute("user",ucount);//登录成功后写入session值
				    result =  Msg.success();
				    result.setExtend(msg.getExtend());
				    return result;			
			}
			else {
				String sex = "";
				String uccount = ShareCodeUtil.getRamdomCount();
				if(info.getGender().equals("m")) 
					sex = "男";
				else
					sex = "女";
				if(userservice.insUserByAlipayId(uccount,info.getUserId(), sex, info.getNick_name(), info.getAvatar(),req)==1) {
					result = Msg.success();
					req.getSession().setAttribute("user",uccount);//登录成功后写入session值
					result.setCode(300);
					result.setMsg("登录并注册成功");
					
				}else {
					result = Msg.success();
					result.setCode(400);
					result.setMsg("登录注册失败");
				
				}
				return result;
			}
		}
		else {
	            result = Msg.fail();
	            result.setMsg("授权令牌获取失败");
	            return result;
		}
	}
	
	
	
	
	/**
	 * 验证码登录
	 */
	@RequestMapping(value="loginBySms",method=RequestMethod.POST)
	public Msg loginBySms(String phone,String code,HttpServletRequest req) {
		Msg msg;
		if(req.getSession().getAttribute(phone).equals(code)) {
			msg = Msg.success();
			req.getSession().setAttribute("user", phone);
			
		}else {
			msg = Msg.fail();
		}
		return msg;
	}
	
	
	
	/**
	 * 获取签名信息和加签信息
	 */
	@RequestMapping(value="getauthInfo",method=RequestMethod.GET)
	@ApiOperation(value="获取签名信息和加签信息")
	public @ResponseBody String getauthInfo(HttpServletRequest req) {
			String uccount = ShareCodeUtil.getRamdomCount();
			Map<String, String> authInfoMap = OrderInfoUtil2_0.buildAuthInfoMap(Context.PID, Context.APP_ID, uccount, true);
			String info = OrderInfoUtil2_0.buildOrderParam(authInfoMap);
			String sign = OrderInfoUtil2_0.getSign(authInfoMap, Context.APP_PRIVATE_KEY, true);
			String authInfo = info + "&" + sign;
			return authInfo;
	}
}
